package com.gateway.aop

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager
import com.alibaba.csp.sentinel.slots.block.RuleConstant
import com.yfree.config.YConfig
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.event.ApplicationStartedEvent
import org.springframework.context.ApplicationListener
import org.springframework.stereotype.Component

@Component
class ApplicationStartAop : ApplicationListener<ApplicationStartedEvent> {
    @Value("\${spring.profiles.active}")
    private lateinit var active: String

    override fun onApplicationEvent(event: ApplicationStartedEvent) {
        YConfig.DEBUG = active != "release"
        //网关QPS流控，每秒限制二次
        GatewayRuleManager.loadRules(
            setOf(
                GatewayFlowRule("baidu").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("api-api").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("api-manager").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("api-service1").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("api-service2").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("api-socket").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1),
                GatewayFlowRule("web-manager").setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(2.0).setIntervalSec(1)
            )
        )
    }
}
